package com.luca.framework.security.filter;

import com.luca.common.enums.HttpMethod;
import com.luca.common.utils.StringUtils;
import com.luca.framework.security.CustomerAuthenticationToken;
import com.luca.framework.security.CustomerUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义身份验证拦截器
 *
 * @author luca
 */
public class CustomerAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public static final String SPRING_SECURITY_FORM_CODE_KEY = "code";

    private String codeParameter = SPRING_SECURITY_FORM_CODE_KEY;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 登录请求只允许post
        if (StringUtils.equals(HttpMethod.POST.name(), request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        String code = obtainCode(request);
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        if (code == null) {
            code = "";
        }
        if (username == null) {
            username = "";
        }
        if (password == null) {
            password = "";
        }
        username = username.trim();
        var authRequest = new CustomerAuthenticationToken(username, password, code);
        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainCode(HttpServletRequest request) {
        return request.getParameter(codeParameter);
    }
}
